package com.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class AiService {

    private static final String API_URL = "https://openrouter.ai/api/v1/chat/completions";
    private static final String API_KEY = "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";

    public JSONObject getAiResponse(String question) {
        System.out.println("question:" + question);
        try {
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
            connection.setRequestProperty("HTTP-Referer", "https://openrouter.ai");
            connection.setRequestProperty("X-Title", "cf");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            JSONObject massage1a = new JSONObject().fluentPut("role", "system").fluentPut("content", "你是王尔政，是考研考公平台的助手机器人");
            JSONObject massagea = new JSONObject().fluentPut("role", "user").fluentPut("content", question);

            String jsonInputString = new JSONObject()
                    .fluentPut("model", "agentica-org/deepcoder-14b-preview:free")
                    .fluentPut("reasoning", new JSONObject().fluentPut("exclude", true))
                    .fluentPut("messages", new JSONObject[]{massage1a,massagea})
                    .fluentPut("modalities", new String[]{"text"})
                    .toJSONString();
            //打印一下 jsonInputString
            System.out.println("jsonInputString:" + jsonInputString);
//            String body = "userName=zhangsan&password=123456";
//            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
//            writer.write(body);
//            writer.close();

            connection.getOutputStream().write(jsonInputString.getBytes(StandardCharsets.UTF_8));

            int responseCode = connection.getResponseCode();
           String msg = connection.getResponseMessage();
            System.out.println("msg:" + msg);
            // 打印响应的所有信息
            System.out.println("Response Code : " + responseCode);
            if (responseCode != HttpURLConnection.HTTP_OK) {
                // 读取错误流以获取详细错误信息
                try (InputStream errorStream = connection.getErrorStream()) {
                    if (errorStream != null) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8));
                        StringBuilder errorMessageBuilder = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            errorMessageBuilder.append(line);
                        }
                        throw new RuntimeException("Failed : HTTP error code : " + responseCode + ", Error message: " + errorMessageBuilder.toString());
                    } else {
                        throw new RuntimeException("Failed : HTTP error code : " + responseCode);
                    }
                }
            }


            // 修复部分：将 InputStream 转换为字符串并解析为 JSONObject
            try (InputStream is = connection.getInputStream()) {
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                System.out.println("response:" + response.toString());
                return JSONObject.parseObject(response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new JSONObject().fluentPut("error", e.getMessage());
        }
    }
}
